<template>
  <div class="createPost-container">

    <sticky :className="'sub-navbar'" :z-index="$upZindex">

      <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="back">{{$t('table.back')}}
      </el-button>

      <el-button v-if="opt!='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="createData">{{$t('table.submit')}}
      </el-button>

      
    

    </sticky>


    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="150px" style='width: 60%; margin-left:10px;margin-top:20px;'>
      <div v-if="opt=='info'">
        <div class="divide-line">作品信息</div>
        <el-form-item label="作品名称" prop="worksName">
          <el-input :disabled="disabled" v-model="postForm.worksName" placeholder="单行输入" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="作品类型" prop="worksType">
          <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.worksType" placeholder="请选择">
            <el-option v-for="item in $worksTypeOptions" :key="item.key" :label="item.label" :value="item.key">
            </el-option>
          </el-select>
          <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.worksType | $worksTypeFilter" placeholder="无" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="关联ID" prop="copyrightId">
          <el-input :disabled="disabled" v-model="postForm.copyrightId" placeholder="请输入" style="width: 200px;"></el-input>
        </el-form-item>
        <div v-if="postForm.worksType=='WorksSingle'">
          <el-form-item label="ISBN号" prop="isbnNo">
            <el-input :disabled="disabled" v-model="postForm.isbnNo" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="出版社" prop="publishingName">
            <el-input :disabled="disabled" v-model="postForm.publishingName" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="文字作者" prop="authorName">
            <el-input :disabled="disabled" v-model="postForm.authorName" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="出版日期" prop="publicationDate">
            <el-date-picker :disabled="disabled" v-model="postForm.publicationDate" type="date" format="yyyy-MM-dd"  value-format="yyyy-MM-dd" placeholder="请选择日期" style="width: 200px;">
            </el-date-picker>
          </el-form-item>
        </div>

        <!-- 听书合辑内容 -->
        <div v-if="postForm.worksType=='ListeningCollection'">
          <el-form-item label="主播" prop="anchorName">
            <el-input :disabled="disabled" v-model="postForm.anchorName" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="集数" prop="seriesNum">
            <el-input :disabled="disabled" v-model="postForm.seriesNum" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="定价" prop="worksPrice">
            <el-input :disabled="disabled" v-model="postForm.worksPrice" placeholder="请输入" style="width: 200px;"></el-input>
          </el-form-item>
        </div>
        <!-- 听书合辑内容 -->
        <el-form-item label="作品简介" prop="worksIntroduction">
          <el-input :disabled="disabled" type="textarea" v-model="postForm.worksIntroduction" placeholder="请输入"  style="width: 400px;" :autosize="{ minRows: 3, maxRows: 5}"></el-input>
        </el-form-item>

        <el-form-item v-if="opt=='info'" label="作品背景" prop="background">
          <el-input :disabled="disabled" :value="postForm.background | $backgroundFilter" placeholder="无" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :disabled="disabled" type="textarea" v-model="postForm.remark" placeholder="请输入"  style="width: 400px;" :autosize="{ minRows: 3, maxRows: 5}"></el-input>
        </el-form-item>
      </div>

      <div class="divide-line">授权信息</div>

      <el-form-item label="版权号" prop="copyrightsNo">
        <el-autocomplete v-if="opt!='info'" :disabled="disabled"
                         v-model="postForm.copyrightsNo"
                         :fetch-suggestions="queryCopyrights"
                         @select="handleCopyrightsSelect"
                         placeholder="请选择版权号"
                         style="width: 200px;"
        >
        </el-autocomplete>

        <el-input v-if="opt=='info'" :disabled="disabled" v-model="postForm.copyrightsNo" placeholder="无" style="width: 200px;"></el-input>
      </el-form-item>

      <el-form-item hidden="true" label="供应商主键" prop="supplyId">
        <el-input v-model="postForm.supplyId" style="width: 200px" ></el-input>
      </el-form-item>
      <el-form-item hidden="true" label="版权主键" prop="copyrightId">
        <el-input v-model="postForm.copyrightId" style="width: 200px" ></el-input>
      </el-form-item>

      <el-form-item label="合同编号" prop="contractNo">
        <el-autocomplete v-if="opt!='info'" :disabled="disabled"
                         v-model="postForm.contractNo"
                         :fetch-suggestions="queryContractIn"
                         @select="handleContractSelect"
                         placeholder="请选择合同"
                         style="width: 200px;"
        >
        </el-autocomplete>

        <el-input v-if="opt=='info'" :disabled="disabled" v-model="postForm.contractNo" placeholder="无" style="width: 200px;"></el-input>
      </el-form-item>

      <el-form-item label="所授权利" prop="copyrightClass">
        <el-checkbox-group :disabled="disabled" v-model="postForm.copyrightClass">
          <el-checkbox v-for="item in $copyrightClassOptions" :label="item.key" :key="item.key">{{item.label}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="是否独家授权" prop="soleFlag">
        <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.soleFlag" placeholder="请选择">
          <el-option v-for="item in $ynOptions" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
        <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.soleFlag | $tfFilter" placeholder="无" style="width: 200px;"></el-input>

      </el-form-item>
      <el-form-item label="有无转授权" prop="subRightsFlag">
        <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.subRightsFlag" placeholder="请选择">
          <el-option v-for="item in $tfOptions" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
        <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.subRightsFlag | $tfFilter" placeholder="无" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item label="有无补协议" prop="protocolFlag">
        <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.protocolFlag" placeholder="请选择">
          <el-option v-for="item in $tfOptions" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
        <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.protocolFlag | $tfFilter" placeholder="无" style="width: 200px;"></el-input>
      </el-form-item>

      <el-form-item label="补充协议合同编号" prop="protocolNo">
        <el-input :disabled="disabled" v-model="postForm.protocolNo" style="width: 200px" ></el-input>
      </el-form-item>


      <el-form-item label="开始时间" prop="beginDate">
        <el-date-picker :disabled="disabled" v-model="postForm.beginDate" type="date" :picker-options="pickerBeginDateBefore" format="yyyy-MM-dd"  value-format="yyyy-MM-dd" placeholder="请选择日期" style="width: 200px;" @change="changeTime">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="终止时间" prop="endDate">
        <el-date-picker :disabled="disabled" v-model="postForm.endDate" type="date" :picker-options="pickerBeginDateAfter" format="yyyy-MM-dd"  value-format="yyyy-MM-dd" placeholder="请选择日期" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="权限使用范围" prop="copyrightsRange">
        <el-checkbox-group :disabled="disabled" v-model="postForm.copyrightsRange" @change="keepOriginCheckBox">
          <el-checkbox v-for="range in $copyrightsRangeOptions" :label="range.key" :key="range.key">{{range.label}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="使用平台" prop="usedPlatform">
        <el-checkbox-group :disabled="disabled" v-model="postForm.usedPlatform"  @change="keepOriginCheckBox">
          <el-checkbox v-model="postForm.usedPlatform" v-for="usedPlatform in $usedPlatformOptions" :label="usedPlatform.key" :key="usedPlatform.key">{{usedPlatform.label}}</el-checkbox>
        </el-checkbox-group>

      </el-form-item>
      <el-form-item label="原始版权" prop="originalCopyrightsFlag">
        <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.originalCopyrightsFlag" placeholder="请选择">
          <el-option v-for="item in $provideOptions" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
        <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.originalCopyrightsFlag | $tfFilter" placeholder="无" style="width: 200px;"></el-input>


      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input :disabled="disabled" type="textarea" v-model="postForm.remark" placeholder="请输入"  style="width: 400px;" :autosize="{ minRows: 3, maxRows: 5}"></el-input>
      </el-form-item>


      <div class="divide-line">结算信息</div>

      <el-form-item label="结算形式" prop="balanceType">
        <el-select v-if="opt!='info'" :disabled="disabled" style="width: 200px" class="filter-item" v-model="postForm.balanceType" placeholder="请选择">
          <el-option v-for="item in $balanceTypeOptions" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>

        <el-input v-if="opt=='info'" :disabled="disabled" :value="postForm.balanceType | $balanceTypeFilter" placeholder="无" style="width: 200px;"></el-input>
      </el-form-item>


      <el-form-item :label="amountLabelMap[this.postForm.balanceType]" v-if="postForm.balanceType!='DIVIDE'" prop="balance">
        <input class="el-input__inner" v-model="postForm.balance" placeholder="请输入数字(单位:元)">
      </el-form-item>

      <div v-if="postForm.balanceType!='BUY'">
        <el-form-item label="甲方比例" prop="partyOneNum">
          <el-input :disabled="disabled" v-model="postForm.partyOneNum" placeholder="请输入数字" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="乙方比例" prop="partyTwoNum">
          <el-input v-if="postForm.contractNum=='2'" readonly="readonly" v-model="postForm.partyTwoNum" placeholder="请输入数字" style="width: 200px;"></el-input>

          <el-input v-if="postForm.contractNum!='2'" v-model="postForm.partyTwoNum" placeholder="请输入数字" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item v-if="postForm.contractNum=='3'" label="丙方比例" prop="partyThreeNum">
          <el-input readonly="readonly" v-model="postForm.partyThreeNum" placeholder="请输入数字" style="width: 200px;"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="结算说明" prop="balanceRemark">
        <el-input :disabled="disabled" type="textarea" v-model="postForm.balanceRemark" placeholder="请输入" style="width: 400px;" :autosize="{ minRows: 3, maxRows: 5}"></el-input>
      </el-form-item>

      <div v-if="opt=='info'">
        <el-form-item label="营业执照/身份证" prop="certNo">
          <el-input :disabled="disabled" v-model="postForm.certNo" placeholder="请输入" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item label="账户名" prop="accountName">
          <el-input :disabled="disabled" v-model="postForm.accountName" placeholder="请输入" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="开户行" prop="bankName">
          <el-input :disabled="disabled" v-model="postForm.bankName" placeholder="请输入" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="bankNo">
          <el-input :disabled="disabled" v-model="postForm.bankNo" placeholder="请输入" style="width: 200px;"></el-input>
        </el-form-item>
      </div>

    </el-form>

    <div v-if="opt=='info'">
      <div class="divide-line-long">合同信息</div>
      <SupplyContractList :contractNo="postForm.contractNo"></SupplyContractList>


      <div style="margin-bottom: 30px" align="center">
        <el-button v-has="'contractRightsTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}</el-button>
        <el-button v-has="'contractRightsTable_disable'" type="danger" size="large" @click="handleInvalid">{{$t('table.invalid')}}</el-button>
      </div>
    </div>

  </div>

</template>

<script>
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { fetchCopyrightsList, checkCopyrightsDate } from '@/api/copyrights/copyrights'

  import { infoContractRights, createContractRights, updateContractRights, invalidContractRights } from '@/api/contractRights/contractRights'

  import { fetchContractList } from '@/api/supplyContract/supplyContract'

  import SupplyContractList from '@/views/components/SupplyContractList'

  const defaultForm = {
    code: ''
  }

  export default {
    name: 'copyrightAdd',
    components: { Sticky, SupplyContractList },
    data() {
      return {
        postForm: Object.assign({
          balanceType: 'BUY',
          contractType: 'IN',
          contractNum: '2',
          contractNo: '',
          copyrightsRange: [],
          usedPlatform: [],
          copyrightClass: [],
          beginDate: '',
          endDate: '',
          soleFlag: '',
          subRightsFlag: '',
          protocolFlag: '',
          originalCopyrightsFlag: '',
          copyrightId: '',
          supplyId: '',
          partyOneNum: '',
          partyTwoNum: '',
          partyThreeNum: '',
          anchorName: ''
        }, defaultForm),
        loading: false,
        rules: {
          copyrightsNo: [{ required: true, message: '请填写唯一版权号', trigger: 'change' }],
          contractNo: [{ required: true, message: '请填写合同编号', trigger: 'change' }],
          copyrightClass: [{ required: true, message: '请填写版权权利', trigger: 'blur' }],
          soleFlag: [{ required: true, message: '请填写是否独家授权', trigger: 'blur' }],
          subRightsFlag: [{ required: true, message: '请填写有无转授权', trigger: 'blur' }],
          protocolFlag: [{ required: true, message: '请填写有无补充协议', trigger: 'blur' }],
          protocolNo: [
            { max: 60, message: '补充协议合同编号过长', trigger: 'blur' }
          ],
          beginDate: [{ required: true, message: '请填写开始时间', trigger: 'blur' }],
          endDate: [{ required: true, message: '请填写终止时间', trigger: 'blur' }],
          copyrightsRange: [{ required: true, message: '请填写权限使用范围', trigger: 'blur' }],
          usedPlatform: [{ required: true, message: '请填写使用平台', trigger: 'blur' }],
          originalCopyrightsFlag: [{ required: true, message: '请填写原始版权', trigger: 'blur' }],
          balanceType: [{ required: true, message: '请填写结算形式', trigger: 'blur' }],
          balance: [{ required: true, message: '请填写金额', trigger: 'blur' },
            { max: 15, message: '金额输入过长', trigger: 'blur' }
          ],
          partyOneNum: [{ required: true, message: '请填写甲方比例', trigger: 'blur' },
            { pattern: /^([1-9]?\d)(\.\d{1,2})?$|^100$/, message: '请填写0-100的数字(小数保留2位)', trigger: 'blur' }
          ],
          partyTwoNum: [{ required: true, message: '请填写乙方比例', trigger: 'blur' },
            { pattern: /^([1-9]?\d)(\.\d{1,2})?$|^100$/, message: '请填写0-100的数字(小数保留2位)', trigger: 'blur' }
          ],
          partyThreeNum: [{ required: true, message: '请填写丙方比例', trigger: 'blur' },
            { pattern: /^([1-9]?\d)(\.\d{1,2})?$|^100$/, message: '请填写0-100的数字(小数保留2位)', trigger: 'blur' }
          ],
          publishingName: [
            { required: false, message: '请填写出版社', trigger: 'blur' },
            { max: 30, message: '长度超过30个字符', trigger: 'blur' }
          ],
          authorName: [
            { required: false, message: '请填写文字作者', trigger: 'blur' },
            { max: 30, message: '长度超过30个字符', trigger: 'blur' }
          ],
          remark: [
            { max: 500, message: '备注过长', trigger: 'blur' }
          ],
          balanceRemark: [
            { max: 500, message: '结算说明过长', trigger: 'blur' }
          ]
        },
        listQuery: {
          compoundSearch: undefined,
          expireStatus: undefined,
          clearMethod: undefined,
          contractType: undefined
        },
        copyrightsRangeKeyOptions: ['OVERSEAS', 'MAINLAND', 'GAT'],
        amountLabelMap: {
          BUY: '买断金额',
          PrePayDivide: '预付金额',
          MixClear: '涉及金额',
          DIVIDE: '无金额'
        },
        disabled: false,
        opt: '',
        pickerBeginDateBefore: {
          disabledDate: (time) => {
            const beginDateVal = this.postForm.beginDate
            if (beginDateVal) {
              return time.getTime() > beginDateVal
            }
          }
        },
        pickerBeginDateAfter: {
          disabledDate: (time) => {
            const beginDateVal = this.postForm.beginDate
            if (beginDateVal) {
              return time.getTime() < beginDateVal
            }
          }
        },
        range_org: {},
        platform_org: {},
        copyrightClass_org: {}
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      },
      balance() {
        return this.postForm.balance
      },
      // partyOneNum() {
      //   return this.postForm.partyOneNum
      // },
      // partyTwoNum() {
      //   return this.postForm.partyTwoNum
      // },
      // partyThreeNum() {
      //   return this.postForm.partyThreeNum
      // }
      balanceTotal() {
        const total = Number(this.postForm.partyOneNum) + Number(this.postForm.partyTwoNum) + Number(this.postForm.partyThreeNum)
        return total
      }
    },
    created() {
      const id = this.$route.query.id
      const opt = this.$route.query.opt
      if (id != null) {
        var params = { id: id, opt: opt }
        infoContractRights(params).then(response => {
          if (response.success) {
            this.postForm = Object.assign({}, response.content) // copy obj
            // 权限使用范围选中状态
            const rangestr = response.content.copyrightsRange
            const copyrightsRange = []
            if (rangestr) {
              const ranges = rangestr.split(',')
              for (var range in ranges) {
                copyrightsRange.push(ranges[range])
              }
            }
            this.postForm.copyrightsRange = copyrightsRange
            // 使用平台选中状态
            const platformstr = response.content.usedPlatform
            const usedPlatform = []
            if (platformstr) {
              const platforms = platformstr.split(',')
              for (var platform in platforms) {
                usedPlatform.push(platforms[platform])
              }
            }
            this.postForm.usedPlatform = usedPlatform
            // 所授权利
            const copyrightClassstr = response.content.copyrightClass
            const copyrightClass = []
            if (copyrightClassstr) {
              const copyrightClasses = copyrightClassstr.split(',')
              for (var item in copyrightClasses) {
                copyrightClass.push(copyrightClasses[item])
              }
            }
            this.postForm.copyrightClass = copyrightClass
            // 记录老版权号用于比较
            this.oldCopyrightsNo = this.postForm.copyrightsNo
            this.oldContractNo = this.postForm.contractNo
            // 判断是否是详情页面
            this.opt = this.$route.query.opt
            if (this.opt === 'info') {
              this.disabled = true
              this.range_org = this.postForm.copyrightsRange
              this.platform_org = this.postForm.usedPlatform
              this.copyrightClass_org = this.postForm.copyrightClass
            }
            if (this.postForm.partyThreeNum) {
              this.postForm.contractNum = 3
            }
          } else {
            this.postForm.id = null
            this.$message({
              type: 'fail',
              message: response.message
            })
            this.$router.go(-1)
          }
        }).catch((error) => {
          this.postForm.id = null
          console.log(error)
        })
      }
    },
    filters: {

    },
    methods: {
      submitForm() {},
      createData() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            const copyrightsRange = this.postForm.copyrightsRange
            const usedPlatform = this.postForm.usedPlatform
            const copyrightClass = this.postForm.copyrightClass
            var copyrightsRange_sub = ''
            var usedPlatform_sub = ''
            var copyrightClass_sub = ''
            // 拼接权限使用范围
            for (var i = 0; i < copyrightsRange.length; i++) {
              var item = copyrightsRange[i]
              if (item !== 'true') {
                copyrightsRange_sub += item
                if (i !== copyrightsRange.length - 1) {
                  copyrightsRange_sub += ','
                }
              }
            }
            // 拼接所授权利
            for (var j = 0; j < copyrightClass.length; j++) {
              var item_j = copyrightClass[j]
              if (item_j !== 'true') {
                copyrightClass_sub += item_j
                if (j !== copyrightClass.length - 1) {
                  copyrightClass_sub += ','
                }
              }
            }
            // 拼接使用平台
            for (var k = 0; k < usedPlatform.length; k++) {
              var item_k = usedPlatform[k]
              if (item_k !== 'true') {
                usedPlatform_sub += item_k
                if (k !== usedPlatform.length - 1) {
                  usedPlatform_sub += ','
                }
              }
            }

            Object.assign(this.postForm, { 'copyrightsRange': copyrightsRange_sub })
            Object.assign(this.postForm, { 'usedPlatform': usedPlatform_sub })
            Object.assign(this.postForm, { 'copyrightClass': copyrightClass_sub })

            // 根据是否有id来判断
            if (this.postForm.id != null) {
              updateContractRights(this.postForm).then(response => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'contractRightsTable' })
                } else {
                  this.$notify({
                    title: '失败',
                    message: '更新失败',
                    type: 'fail',
                    duration: 2000
                  })
                }
              })
            } else {
              createContractRights(this.postForm).then((response) => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'contractRightsTable' })
                } else {
                  this.$notify({
                    title: '失败',
                    message: '创建失败',
                    type: 'fail',
                    duration: 2000
                  })
                }
              })
            }
            this.postForm.copyrightsRange = copyrightsRange
            this.postForm.usedPlatform = usedPlatform
            this.postForm.copyrightClass = copyrightClass
          }
        })
      },
      // 版权编号选择
      queryCopyrights(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'copyrightsNo': this.postForm.copyrightsNo }

        fetchCopyrightsList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.copyrightsNo })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 版权选择后的回调
      handleCopyrightsSelect(item) {
        // 校验
        if (item.copyrightsNo == null || item.copyrightsNo === '' || item.copyrightsNo === this.oldCopyrightsNo) {
          return
        }
        const params = { 'copyrightsNo': item.copyrightsNo }
        checkCopyrightsDate(params).then((response) => {
          if (!response.success) {
            this.$message(response.message)
            this.postForm.copyrightsNo = ''
          } else {
            // 赋值
            this.postForm.beginDate = item.beginDate
            this.postForm.endDate = item.endDate
  
            // 合同号不同,结算信息来源于合同号
            // this.postForm.contractNo = item.contractNo;
            // this.postForm.balanceType = item.balanceType;
            // this.postForm.balance = item.balance;
            // this.postForm.partyOne = item.partyOne;
            // this.postForm.partyOneNum = item.partyOneNum;
            // this.postForm.partyTwo = item.partyTwo;
            // this.postForm.partyTwoNum = item.partyTwoNum;
            // this.postForm.partyThree = item.partyThree;
            // this.postForm.partyThreeNum = item.partyThreeNum;
            // this.postForm.balanceRemark = item.balanceRemark;
  
            this.postForm.copyrightClass = item.copyrightClass
            this.postForm.soleFlag = item.soleFlag
            this.postForm.subRightsFlag = item.subRightsFlag
            this.postForm.protocolFlag = item.protocolFlag
            this.postForm.usedPlatform = item.usedPlatform.split(',')
            this.postForm.copyrightsRange = item.copyrightsRange.split(',')
            this.postForm.copyrightClass = item.copyrightClass.split(',')
            this.postForm.originalCopyrightsFlag = item.originalCopyrightsFlag

            this.postForm.copyrightId = item.id
            this.postForm.supplyId = item.supplyId
          }
        }).catch((error) => {
          console.log(error)
          this.postForm.copyrightsNo = ''
        })
      },
      checkCopyrightsDate() {
        if (this.postForm.copyrightsNo == null || this.postForm.copyrightsNo === '' || this.postForm.copyrightsNo === this.oldCopyrightsNo) {
          return
        }
        const params = { 'copyrightsNo': this.postForm.copyrightsNo }
        checkCopyrightsDate(params).then((response) => {
          if (!response.success) {
            this.$message(response.message)
            this.postForm.copyrightsNo = ''
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 合同编号选择
      queryContractIn(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'contractNo': this.postForm.contractNo }

        fetchContractList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.contractNo })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 合同选择后的回调
      handleContractSelect(item) {
        // 赋值
        // 若为复合结算,则不自动填入
        const balanceType = item.balanceType
        if (balanceType !== 'MixClear') {
          this.postForm.balanceType = item.balanceType
          this.postForm.balance = item.totalAmount + ''
          this.postForm.partyOne = item.partyOne
          this.postForm.partyOneNum = item.partyOneNum
          this.postForm.partyTwo = item.partyTwo
          this.postForm.partyTwoNum = item.partyTwoNum
          this.postForm.partyThree = item.partyThree
          this.postForm.partyThreeNum = item.partyThreeNum
          this.postForm.balanceRemark = item.balanceRemark
        } else {
          this.postForm.balanceType = 'BUY'
          this.postForm.balance = ''
          this.postForm.partyOne = ''
          this.postForm.partyOneNum = ''
          this.postForm.partyTwo = ''
          this.postForm.partyTwoNum = ''
          this.postForm.partyThree = ''
          this.postForm.partyThreeNum = ''
          this.postForm.balanceRemark = ''
        }
        this.postForm.supplyId = item.supplyId
        this.postForm.contractNum = item.contractNum
      },
      // 返回
      back() {
        // this.$router.push({ name: 'contractRightsTable' })
        history.go(-1)
      },
      keepOriginCheckBox() {
        if (this.opt === 'info') {
          this.postForm.copyrightsRange = this.range_org
          this.postForm.usedPlatform = this.platform_org
          this.postForm.copyrightClass = this.copyrightClass_org
        }
      },
      handleUpdate() {
        this.$router.push({ name: 'contractRightsEdit', query: { id: this.postForm.id }})
      },
      handleInvalid() {
        this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用失效接口
          var p = { id: this.postForm.id }
          invalidContractRights(p).then(response => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$router.push({ name: 'contractRightsTable' })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 选择开始时间，清空结束时间
      changeTime(date) {
        this.postForm.endDate = ''
        this.pickerBeginDateAfter = {
          disabledDate(time) { // 开始时间-结束时间
            return (time.getTime() < new Date(date).getTime())
          }
        }
      }
    },
    watch: {
      '$route'(to, from) {
        if (from.name === 'contractRightsInfo' || from.name === 'contractRightsEdit') {
          this.$router.go(0)
        }
      },
      balance() {
        this.postForm.balance = (this.postForm.balance + '').match(/\d+(\.\d{0,2})?/) ? (this.postForm.balance + '').match(/\d+(\.\d{0,2})?/)[0] : ''
      },
      // partyOneNum() {
      //   this.postForm.partyOneNum = (this.postForm.partyOneNum + '').match(/\d+(\.\d{0,2})?/) ? (this.postForm.partyOneNum + '').match(/\d+(\.\d{0,2})?/)[0] : ''
      // },
      // partyTwoNum() {
      //   this.postForm.partyTwoNum = (this.postForm.partyTwoNum + '').match(/\d+(\.\d{0,2})?/) ? (this.postForm.partyTwoNum + '').match(/\d+(\.\d{0,2})?/)[0] : ''
      // },
      // partyThreeNum() {
      //   this.postForm.partyThreeNum = (this.postForm.partyThreeNum + '').match(/\d+(\.\d{0,2})?/) ? (this.postForm.partyThreeNum + '').match(/\d+(\.\d{0,2})?/)[0] : ''
      // }
      balanceTotal() {
        if (this.postForm.contractNum === '2' || this.postForm.contractNum === 2) {
          this.postForm.partyTwoNum = (100 - Number(this.postForm.partyOneNum)).toFixed(2)
          if (this.postForm.partyTwoNum.endsWith('.0') || this.postForm.partyTwoNum.endsWith('.00')) {
            this.postForm.partyTwoNum = Number(this.postForm.partyTwoNum).toFixed(0)
          } else if (this.postForm.partyTwoNum.endsWith('0')) {
            this.postForm.partyTwoNum = Number(this.postForm.partyTwoNum).toFixed(1)
          }
          if (this.postForm.partyTwoNum < 0) {
            this.postForm.partyTwoNum = 0
            this.postForm.partyOneNum = 0
          }
          if (this.postForm.partyTwoNum < 0) {
            this.postForm.partyTwoNum = 0
            this.postForm.partyOneNum = 0
          }
          this.postForm.partyThreeNum = 0
        } else {
          this.postForm.partyThreeNum = (100 - Number(this.postForm.partyOneNum) - Number(this.postForm.partyTwoNum)).toFixed(2)
          if (this.postForm.partyThreeNum.endsWith('.0') || this.postForm.partyThreeNum.endsWith('.00')) {
            this.postForm.partyThreeNum = Number(this.postForm.partyThreeNum).toFixed(0)
          } else if (this.postForm.partyThreeNum.endsWith('0')) {
            this.postForm.partyThreeNum = Number(this.postForm.partyThreeNum).toFixed(1)
          }
          if (this.postForm.partyThreeNum < 0) {
            this.postForm.partyThreeNum = 0
            this.postForm.partyTwoNum = 0
            this.postForm.partyOneNum = 0
          }
        }
      }
    }
  }
</script>

<style scoped>
  .el-input__inner {
    width: 200px;
  }
</style>

